package cn.echo.consul.manager.repository;

import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.kv.model.GetValue;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;
import org.yaml.snakeyaml.Yaml;

import java.util.ArrayList;
import java.util.List;

/**
 * consul管理存储
 */
@RequiredArgsConstructor
@Repository
public class ManagerRepository {

    final ConsulClient consulClient;

    /**
     * 获取对象
     */
    public <T> T get(String profile, Class<T> clazz) {
        GetValue result = consulClient.getKVValue(profile).getValue();
        if (result==null || StringUtils.isEmpty(result.getValue())) {
            return null;
        }
        Yaml yaml = new Yaml();
        T entity = yaml.loadAs(result.getDecodedValue(), clazz);
        return entity;
    }

    /**
     * 获取YAML
     */
    public String getYaml(String profile) {
        GetValue result = consulClient.getKVValue(profile).getValue();
        if (result==null || StringUtils.isEmpty(result.getValue())) {
            return null;
        }
        return result.getDecodedValue();
    }

    /**
     * 获取对象列表
     */
    public <T> List<T> getList(String profile, Class<T> clazz) {
        List<T> list = new ArrayList<>();
        List<GetValue> results = consulClient.getKVValues(profile).getValue();
        if (results==null || results.isEmpty()) {
            return list;
        }
        Yaml yaml = new Yaml();
        for (GetValue result: results) {
            T entity = yaml.loadAs(result.getDecodedValue(), clazz);
            list.add(entity);
        }
        return list;
    }

    /**
     * 更新对象
     */
    public <T> boolean update(String profile, T entity) {
        Yaml yaml = new Yaml();
        String value = yaml.dumpAsMap(entity);

        return consulClient.setKVValue(profile, value).getValue();
    }

    /**
     * 删除对象(物理删除)
     */
    @Deprecated
    public void delete(String profile) {
        consulClient.deleteKVValue(profile).getValue();
    }
}
